# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggplot2)
library(ggrepel)
library(dplyr)
library(tidyr)
library(tibble)
library(ropls)
library(pROC)
library(egg)
library(purrr)
library(stringr)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)
diffData <- read.csv("../../07/Sig_Met.csv", header = T, stringsAsFactors = F, row.names = 1) %>%
    rownames_to_column("Metabolite") %>%
    filter(IS_Final_Pooled_Sig == 1)

diffNames <- diffData %>%
.$Name

data <- read.csv(opt$i, header = T) %>%
    select(- c("HMDB", "KEGG", "Class")) %>%
    filter(Name %in% diffNames) %>%
    gather("SampleID", "Value", - Name) %>%
    spread(Name, "Value") %>%
    inner_join(sampleInfo, by = c("SampleID")) %>%
    column_to_rownames("SampleID") %>%
    mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
    as.data.frame()

x <- data %>% select(- c("ClassNote"))
y <- data$ClassNote

borutaRs <- Boruta(x, y, maxRuns = 500)
decData <- borutaRs$finalDecision %>%
    as.data.frame() %>%
    rownames_to_column("Metabolite") %>%
    set_colnames(c("Metabolite", "decision"))
print(decData)

statData <- attStats(borutaRs) %>%
rownames_to_column("Metabolite")
outData <- statData %>%
    arrange(desc(medianImp)) %>%
    column_to_rownames("Metabolite")
outFileName <- paste0(parent, "/RF_Importance.csv")
write.csv(outData, outFileName)

sortData <- borutaRs$ImpHistory %>%
    t() %>%
    as.data.frame() %>%
    rownames_to_column("Metabolite") %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        data <- result[- 1] %>%
            unlist() %>%
            discard(~ is.infinite(.x))
        median <- median(data, na.rm = T)
        result$median <- median
        result
    }) %>%
    arrange(median) %>%
    as.data.frame()

print(head(outData))

sortNames <- sortData$Name

decLelvels <- c("Shadow", "Rejected", "Tentative", "Confirmed")
fillColors <- setNames(c("#0000FF", "#FF0000", "#FFFF00", "#00FF00"), decLelvels)

imp <- borutaRs$ImpHistory %>%
    t() %>%
    as.data.frame() %>%
    rownames_to_column("Metabolite") %>%
    gather("Sample", "Value", - Name) %>%
    left_join(decData, by = c("Metabolite")) %>%
    mutate_at(vars("decision"), function(x){
        ifelse(is.na(x), "Shadow", as.character(x))
    }) %>%
    mutate(Name = factor(Name, levels = sortNames)) %>%
    mutate(decision = factor(decision, levels = decLelvels)) %>%
    as.data.frame()

head(imp)


p <- ggplot(imp, mapping = aes(x = Name, y = Value, fill = decision)) +
    ylab("Importance") +
    xlab("") +
    theme_bw(base_size = 8.8, base_family = "Times") +
    theme(axis.text.x = element_text(angle = 45, size = 9, hjust = 1, vjust = 1), legend.position = 'top',
    legend.text = element_text(size = 9), legend.title = element_text(size = 11),
    axis.text.y = element_text(size = 8.8), axis.title.y = element_text(size = 11),
    axis.title.x = element_text(size = 12), panel.border = element_rect(size = 0.75)
    ) +
    geom_boxplot() +
    scale_fill_manual("finalDecision", values = fillColors)

pdfFileName <- paste0(parent, "/RF_Importance.pdf")
ggsave(limitsize = FALSE,pdfFileName, p, width = 10, height = 6)









